using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Consts;
using AvalonAdmin.Helpers;
using AvalonAdmin.Models;
using AvalonAdmin.Pages.CarVin.Views;
using AvalonAdminDto.CarVin.VINDtos;
using AvalonAdminDto.Common;
using AvalonAdminDto.Rule.RuleConfigDtos;
using Avalonia.Controls;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.Input;
using D.UtilCore.Dtos;
using D.UtilFreesqlOrm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.CarVin.ViewModels
{
    /// <summary>
    /// VIN查询视图模型
    /// </summary>
    public class VINQueryViewModel : SimpleIntegratedViewModel<RepVINInfo>
    {
        #region 私有字段
        private string? _vin;
        private string? _vehicleModel;
        private string? _engineModel;
        private ObservableCollection<VINMapping> _dataRuleMapping = new();
        #endregion

        #region 查询条件属性

        /// <summary>
        /// VIN码
        /// </summary>
        public string? VIN
        {
            get => _vin;
            set => SetProperty(ref _vin, value);
        }

        /// <summary>
        /// 车型
        /// </summary>
        public string? VehicleModel
        {
            get => _vehicleModel;
            set => SetProperty(ref _vehicleModel, value);
        }

        /// <summary>
        /// 发动机型号
        /// </summary>
        public string? EngineModel
        {
            get => _engineModel;
            set => SetProperty(ref _engineModel, value);
        }
        
        /// <summary>
        /// 规则映射数据
        /// </summary>
        public ObservableCollection<VINMapping> DataRuleMapping
        {
            get => _dataRuleMapping;
            set => SetProperty(ref _dataRuleMapping, value);
        }

        /// <summary>
        /// 更新按钮是否启用
        /// </summary>
        public bool UpdateBtnEnabled => CanUpdate(SelectedModel);

        /// <summary>
        /// 删除按钮是否启用
        /// </summary>
        public bool DeleteBtnEnabled => CanDelete(SelectedModel);

        /// <summary>
        /// 批量删除按钮是否启用
        /// </summary>
        public bool BatchDeleteBtnEnabled => CanBatchDelete();
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public VINQueryViewModel()
        {
            InitializeButtons();
            // 立即刷新命令状态，确保按钮在页面加载时可用
            Dispatcher.UIThread.Post(() => 
            {
                OnPropertyChanged(nameof(UpdateBtnEnabled));
                OnPropertyChanged(nameof(DeleteBtnEnabled));
                OnPropertyChanged(nameof(BatchDeleteBtnEnabled));
                RefreshCommandStates();
            });
            _ = Task.Run(async () => await QueryAsync());
        }
        #endregion

        #region 重写方法
        /// <summary>
        /// 重写选中模型改变事件，同时刷新按钮启用状态
        /// </summary>
        protected override void OnSelectedModelChanged()
        {
            base.OnSelectedModelChanged();
            if (SelectedModel != null)
            {
                _ = Task.Run(async () => await SelectedModelChangeAsync(SelectedModel));
            }
            else
            {
                DataRuleMapping.Clear();
            }
            
            OnPropertyChanged(nameof(UpdateBtnEnabled));
            OnPropertyChanged(nameof(DeleteBtnEnabled));
        }

        /// <summary>
        /// 重写数据改变事件，同时刷新按钮启用状态
        /// </summary>
        protected override void OnDataChanged()
        {
            base.OnDataChanged();
            OnPropertyChanged(nameof(UpdateBtnEnabled));
            OnPropertyChanged(nameof(DeleteBtnEnabled));
            OnPropertyChanged(nameof(BatchDeleteBtnEnabled));
        }
        #endregion

        #region SimpleIntegratedViewModel 抽象方法实现
        /// <summary>
        /// 重置查询条件
        /// </summary>
        public void ResetQuery()
        {
            VIN = string.Empty;
            VehicleModel = string.Empty;
            EngineModel = string.Empty;
        }

        /// <summary>
        /// 异步查询数据
        /// </summary>
        public override async Task QueryAsync()
        {
            try
            {
                var queryParams = new
                {
                    VIN = VIN?.Trim(),
                    VehicleModel = VehicleModel?.Trim(),
                    EngineModel = EngineModel?.Trim(),
                    PageNo = PageNo,
                    PageSize = PageSize
                };

                var res = await HttpHelper<PagedResult<RepVINInfo>>.PostAsync(ApiUrl.QueryVINInfo, queryParams);
                if (res.Code == StatusCodeEnum.OK && res.Data != null)
                {
                    Data = new ObservableCollection<RepVINInfo>(res.Data.Items ?? new List<RepVINInfo>());
                    TotalCount = res.Data.TotalCount;
                }
                else
                {
                    Data = new ObservableCollection<RepVINInfo>();
                    TotalCount = 0;
                    if (!string.IsNullOrEmpty(res.Msg))
                    {
                        ShowError(res.Msg);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError($"查询失败：{ex.Message}");
                Data = new ObservableCollection<RepVINInfo>();
                TotalCount = 0;
            }
        }

        /// <summary>
        /// 添加VIN信息
        /// </summary>
        public override async Task AddAsync(RepVINInfo? obj = default)
        {
            var res = await Dialog.ShowModal<VINModifyPage, VINModifyViewModel>(
                new VINModifyViewModel(viewStatus: ViewStatus.Add),
                null,
                options: GetDialogOptions("添加VIN信息"));
            
            if (res == DialogResult.OK)
            {
                await QueryAsync();
            }
        }

        /// <summary>
        /// 更新VIN信息
        /// </summary>
        public override async Task UpdateAsync(RepVINInfo? obj = default)
        {
            var model = obj ?? SelectedModel;
            if (model == null)
            {
                ShowWarning("请选择要修改的数据");
                return;
            }

            var res = await Dialog.ShowModal<VINModifyPage, VINModifyViewModel>(
                new VINModifyViewModel(model, ViewStatus.Update),
                null,
                options: GetDialogOptions("修改VIN信息"));
            
            if (res == DialogResult.OK)
            {
                await QueryAsync();
            }
        }

        /// <summary>
        /// 删除VIN信息
        /// </summary>
        public override async Task DeleteAsync(RepVINInfo? obj = default)
        {
            var model = obj ?? SelectedModel;
            if (model == null)
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var result = await MessageBox.ShowOverlayAsync(
                "确认删除该VIN信息？",
                "提示",
                icon: MessageBoxIcon.Question,
                button: MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                var res = await HttpHelper<int>.DeleteAsync($"{ApiUrl.DeleteVINInfo}/{model.Id}");
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess("删除成功");
                    await QueryAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "删除失败");
                }
            }
        }

        /// <summary>
        /// 批量删除VIN信息
        /// </summary>
        public override async Task BatchDeleteAsync(IEnumerable<RepVINInfo>? items = null)
        {
            var selectedItems = items?.ToList() ?? GetSelectedItems().ToList();
            if (!selectedItems.Any())
            {
                ShowWarning("请选择要删除的数据");
                return;
            }

            var result = await MessageBox.ShowOverlayAsync(
                $"确认删除选中的 {selectedItems.Count} 条VIN信息？",
                "提示",
                icon: MessageBoxIcon.Question,
                button: MessageBoxButton.OKCancel);

            if (result == MessageBoxResult.OK)
            {
                var ids = selectedItems.Select(x => x.Id).ToList();
                var res = await HttpHelper<int>.PostAsync(ApiUrl.BatchDeleteVINInfo, ids);
                if (res.Code == StatusCodeEnum.OK)
                {
                    ShowSuccess($"成功删除 {selectedItems.Count} 条数据");
                    await QueryAsync();
                }
                else
                {
                    ShowError(res.Msg ?? "批量删除失败");
                }
            }
        }

        /// <summary>
        /// 获取项目的选中状态
        /// </summary>
        protected override bool GetIsSelected(RepVINInfo item) => item.IsSelected;

        /// <summary>
        /// 设置项目的选中状态
        /// </summary>
        protected override void SetIsSelected(RepVINInfo item, bool isSelected) => item.IsSelected = isSelected;
        #endregion

        /// <summary>
        /// 选中事件
        /// </summary>
        /// <param name="repRuleConfig"></param>
        public async Task SelectedModelChangeAsync(RepRuleConfig? repRuleConfig)
        {
            try
            {
                if (repRuleConfig == null || string.IsNullOrWhiteSpace(VIN))
                {
                    return;
                }

                if (DataRuleMapping != null)
                {
                    DataRuleMapping.Clear();
                }
                else
                {
                    DataRuleMapping = new ObservableCollection<VINMapping>();
                }

                var res = await HttpHelper<List<RepRuleMapping>>.PostAsync(ApiUrl.GetRuleMappingByVIN, new RepRuleMappingAndVIN()
                {
                    RuleId = repRuleConfig.Id,
                    VIN = VIN
                });
                
                //  判断结果
                if (res.Code == StatusCodeEnum.Waring)
                {
                    ShowWarning(res.Msg);
                }
                else if (res.Code == StatusCodeEnum.Error)
                {
                    ShowError(res.Msg);
                }
                else if (res.Code == StatusCodeEnum.ServerError)
                {
                    ShowError("服务器异常");
                }
                else if (res.Code == StatusCodeEnum.OK)
                {
                    // 绑定数据源到UI 
                    if (res.Data != null)
                    {
                        foreach (var item in res.Data)
                        {
                            VINMapping vinMapping = new VINMapping();
                            vinMapping.Key = item.Key;
                            vinMapping.Val = item.Val;
                            vinMapping.RegStr = item.RegStr;
                            vinMapping.Descption = item.Descption;
                            vinMapping.Type = (int)item.Details.Type;
                            List<string> displayKeyList = new List<string>();
                            List<string> displayValueList = new List<string>();
                            if (item.Details.ValueDetailsList != null)
                            {
                                foreach (var itemValueDetails in item.Details.ValueDetailsList)
                                {
                                    displayKeyList.Add(itemValueDetails.Key);
                                    displayValueList.Add(itemValueDetails.Value);
                                }
                                vinMapping.DisplayKey = string.Join("\n", displayKeyList);
                                vinMapping.DisplayValue = string.Join("\n", displayValueList);
                            }
                            else
                            {
                                vinMapping.DisplayKey = item.Details?.ReferenceDetails?.Key;
                                vinMapping.DisplayValue = item.Details?.ReferenceDetails?.Value;
                                vinMapping.Id = item.Details?.ReferenceDetails?.Id;
                            }

                            DataRuleMapping.Add(vinMapping);
                        }
                    }
                }
                else
                {
                    ShowError(res.Code.ToString());
                }
            }
            catch (Exception ex)
            {
                ShowError($"查询规则映射失败: {ex.Message}");
            }
        }

        #region 重写方法
        /// <summary>
        /// 选中模型变更事件
        /// </summary>
        protected override void OnSelectedModelChanged()
        {
            base.OnSelectedModelChanged();
            if (SelectedModel != null)
            {
                _ = Task.Run(async () => await SelectedModelChangeAsync(SelectedModel));
            }
            else
            {
                DataRuleMapping.Clear();
            }

            // 更新按钮状态
            OnPropertyChanged(nameof(UpdateBtnEnabled));
            OnPropertyChanged(nameof(DeleteBtnEnabled));
        }

        /// <summary>
        /// 数据变更事件
        /// </summary>
        protected override void OnDataChanged()
        {
            base.OnDataChanged();
            OnPropertyChanged(nameof(BatchDeleteBtnEnabled));
        }

        /// <summary>
        /// 提交查询
        /// </summary>
        /// <returns></returns>
        public async Task Submit()
        {
            await QueryAsync();
        }

        /// <summary>
        /// 重置方法
        /// </summary>
        public override void Reset()
        {
            VIN = string.Empty;
            Data.Clear();
            DataRuleMapping.Clear();
        }

        /// <summary>
        /// 是否可以更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected override bool CanUpdate(RepVINInfo? model)
        {
            return model != null;
        }

        /// <summary>
        /// 是否可以删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        protected override bool CanDelete(RepVINInfo? model)
        {
            return model != null;
        }

        /// <summary>
        /// 是否可以批量删除
        /// </summary>
        /// <returns></returns>
        protected bool CanBatchDelete()
        {
            return Data?.Any(x => x.IsSelected) == true;
        }
        #endregion

        #region 命令
        /// <summary>
        /// 查询命令
        /// </summary>
        private RelayCommand? _queryCommand;
        public RelayCommand QueryCommand => _queryCommand ??= new RelayCommand(async () => await QueryAsync());

        /// <summary>
        /// 重置命令
        /// </summary>
        private RelayCommand? _resetCommand;
        public RelayCommand ResetCommand => _resetCommand ??= new RelayCommand(async () => await Reset());

        /// <summary>
        /// 详细查询事件
        /// </summary>
        private RelayCommand<VINMapping>? _queryVINMappingCommand;
        public RelayCommand<VINMapping> QueryVINMappingCommand => _queryVINMappingCommand ??= new RelayCommand<VINMapping>(QueryVINMapping);

        /// <summary>
        /// 查询VIN映射详情
        /// </summary>
        /// <param name="obj"></param>
        private void QueryVINMapping(VINMapping? obj = null)
        {
            if (obj == null) return;

            switch (obj.Type)
            {
                case 1: _ = ShowBrand(obj.Id); break;
                case 2: _ = ShowVehicleSeries(obj.Id); break;
                case 3: _ = ShowCarType(obj.Id); break;
                case 4: _ = ShowCarTypeVersion(obj.Id); break;
                case 5: _ = ShowCarParts(obj.Id); break;
            }
        }

        /// <summary>
        /// 显示品牌详情
        /// </summary>
        /// <param name="id"></param>
        private async Task ShowBrand(string id)
        {
            await Dialog.ShowModal<Page_Brand_Modify, BrandModifyViewModel>(new BrandModifyViewModel(id, ViewStatus.View),
                null, options: GetDialogOptions("品牌"));
        }
        /// <summary>
        /// 显示车系
        /// </summary>
        /// <param name="id"></param>
        private async Task ShowVehicleSeries(string id)
        {
            await Dialog.ShowModal<Page_VehicleSeries_Modify, VehicleSeriesModifyViewModel>(new VehicleSeriesModifyViewModel(null, id, ViewStatus.View),
                 null, options: GetDialogOptions("车系"));
        }

        /// <summary>
        /// 车型
        /// </summary>
        /// <param name="id"></param>
        private async Task ShowCarType(string id)
        {
            await Dialog.ShowModal<Page_CarType_Modify, CarTypeModifyViewModel>(new CarTypeModifyViewModel(id, ViewStatus.View),
                null, options: GetDialogOptions("车型"));
        }

        /// <summary>
        /// 车型版本
        /// </summary>
        /// <param name="id"></param>
        private async Task ShowCarTypeVersion(string id)
        {
            await Dialog.ShowModal<Page_CarTypeVersion_Modify, CarTypeVersionModifyViewModel>(new CarTypeVersionModifyViewModel(id, ViewStatus.View),
              null, options: GetDialogOptions("车型版本"));
        }

        private async Task ShowCarParts(string id)
        {
            await Dialog.ShowModal<Page_CarParts_Modify, CarPartsModifyViewModel>(new CarPartsModifyViewModel(null, id, string.Empty, ViewStatus.View),
              null, options: GetDialogOptions("配件"));
        }
        #endregion


    }

}


